package cn.tedu.jsd2205the.back.end.project.service.impl;

import cn.tedu.jsd2205the.back.end.project.exception.ServiceException;
import cn.tedu.jsd2205the.back.end.project.mapper.ProductMapper;
import cn.tedu.jsd2205the.back.end.project.pojo.dto.ProductPagerDTO;
import cn.tedu.jsd2205the.back.end.project.pojo.entity.Product;
import cn.tedu.jsd2205the.back.end.project.pojo.vo.ProductDetailVO;
import cn.tedu.jsd2205the.back.end.project.pojo.vo.ProductListItemVO;
import cn.tedu.jsd2205the.back.end.project.pojo.vo.ProductSimpleVO;
import cn.tedu.jsd2205the.back.end.project.restful.ResponseCode;
import cn.tedu.jsd2205the.back.end.project.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public ProductDetailVO selectById(int id) {
        log.debug("根据id 获取商品详情");
        //浏览量加1
        productMapper.increaseViewCount(id);
        ProductListItemVO dbResult = productMapper.selectById(id);
        if (dbResult == null) {
            throw new ServiceException(ResponseCode.BAD_REQUEST, "获取商品详情失败，尝试访问的数据不存在！");
        }
        ProductDetailVO productDetailVO = new ProductDetailVO();
        BeanUtils.copyProperties(dbResult, productDetailVO);
        return productDetailVO;
    }

    @Override
    public ProductSimpleVO selectByName(String name) {
        log.debug("根据名字 获取商品详情");
        productMapper.ViewCountByName(name);
        ProductListItemVO dbResult = productMapper.selectByName(name);
        if (dbResult == null) {
            throw new ServiceException(ResponseCode.BAD_REQUEST, "获取商品详情失败，尝试访问的数据不存在！");
        }
        ProductSimpleVO productSimpleVO=new ProductSimpleVO();
        BeanUtils.copyProperties(dbResult, productSimpleVO);
        return productSimpleVO;
    }

    /**
     * 查询新上架的商品
     * @return
     */
    @Override
    public List<ProductSimpleVO> selectNew() {
        return productMapper.selectNew();
    }

    @Override
    public List<Product> selectByPage(ProductPagerDTO productPagerDTO) {
        // 获取页数和每页的记录数
        Integer page = productPagerDTO.getPage();
        Integer size = productPagerDTO.getSize();

        // 通过页数和记录数计算偏移量
        productPagerDTO.setOffset((page - 1) * size);

        return productMapper.selectByPage(productPagerDTO);
    }

    @Override
    public int selectCountByPage(ProductPagerDTO productPagerDTO) {
        return productMapper.selectCountByPage(productPagerDTO);
    }
}
